package com.Maykk.Demo08;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName: SellTickets
 * @Description: TODO 门票线程类
 * @Author: MaykkStar@163.com
 */
public class SellTickets implements Runnable {
    private static int tickets = 100;
    private static Lock lock = new ReentrantLock();

    @Override
    public void run() {
        while (sellTickets()) ;
    }

    public static boolean sellTickets() {
        boolean b = true;
        lock.lock(); // 线程同步锁 - 上锁
        if (tickets > 0) {
            System.out.println(Thread.currentThread().getName() + "卖出了第" + tickets + "张票");
            tickets--;
        } else {
            System.out.println("票卖完了");
            b = false;
        }
        lock.unlock(); // 解锁，如果不解锁就会形成“死锁”状态
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return b;
    }
}
